#include "searchlistwidget.h"
#include "ui_searchlistwidget.h"
#include <QTimer>
#include "songmanager.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QDebug>
#include <QUrl>
SearchListWidget::SearchListWidget(QWidget *parent) :
    QWidget(parent),
    _manager(new QNetworkAccessManager(this)),
    ui(new Ui::SearchListWidget)
{
    ui->setupUi(this);

    QVBoxLayout *containerLayout = static_cast<QVBoxLayout*>(ui->container->layout());
    containerLayout->setAlignment(Qt::AlignTop);       // 布局内所有子控件顶对齐
    containerLayout->setContentsMargins(60, 0, 57, 0);    // 左边距60, 右边距 60-3

    // ban掉可能出现的横向滑动条
    ui->scrollArea->setWidgetResizable(true);
    ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 永久关掉横向
    ui->scrollArea->viewport()->installEventFilter(this); // 添加事件过滤器来处理滚动区域大小变化
    ui->SearchListWidgetStyle->installEventFilter(this);

    qDebug() << "SearchListWidget()";
}

SearchListWidget::~SearchListWidget()
{
    qDebug() << "~SearchListWidget()";
    delete ui;
}

#include <QResizeEvent>
// 添加事件过滤器函数以处理大小变化
bool SearchListWidget::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->scrollArea->viewport() && event->type() == QEvent::Resize) {
        // 当窗口大小变化时调整container的最小宽度
        QResizeEvent *resizeEvent = (QResizeEvent*)(event);
        int newWidth = resizeEvent->size().width();
        ui->container->setMinimumWidth(newWidth);
    } else if (watched == ui->SearchListWidgetStyle && event->type() == QEvent::Resize) {
        int width = ui->SearchListWidgetStyle->width();
        ui->widget_head->setMaximumWidth(width - 87);
    }

    return QWidget::eventFilter(watched, event);
}

void SearchListWidget::addSongItem(SongItemWidget *songItem)
{
    songItem->setImageSize(70);
//    songItem->hide();
    _songItems.push_back(songItem);
    songItem->setIndex(_songItems.size());
    connect(songItem, &SongItemWidget::played, this, &SearchListWidget::on_songItem_played);
    ui->container->layout()->addWidget(songItem);
//    QTimer::singleShot(666, this, [=](){
//    songItem->show();
//    });
}

void SearchListWidget::search(const QString& searchText)
{
    if(searchText == _old_searchText){
        return;
    }
    _old_searchText = searchText;

    // 清除上次的, 也即每次都搜一次
    clearOldDatas();

    // 设置头部的文字. -- 这句放哪儿待定
    setSearchText(searchText);

    // 创建URL和请求
    QString urlStr = "https://music.163.com/api/search/get/web?s=" + searchText + "&type=1&limit=66&offset=0";
    // 注:type=1搜歌手,limit=66指最多返回66个结果(没找到解除限制的方法,如果显示不设置limit,默认是10个),offset=0即从0开始
    QUrl url(urlStr);
    QNetworkRequest request;
    request.setUrl(url);

    QNetworkReply* reply = _manager->get(request);
    _replys.insert(reply);
    connect(reply, &QNetworkReply::finished, this, [=](){
        this->_replys.remove(reply);
        on_reply_finished(reply);
    });
//    pageSearch(searchText, 10, 0);
}

void SearchListWidget::pageSearch(const QString &searchText, int limit, int offset)
{
    clearOldDatas();

    // 创建URL和请求
    QString urlStr = "https://music.163.com/api/search/get/web?s=" + searchText +
                     "&type=1&limit=" + QString::number(limit) + "&offset=" + QString::number(offset);
    QUrl url(urlStr);
    QNetworkRequest request;
    request.setUrl(url);

    QNetworkReply* reply = _manager->get(request);
    _replys.insert(reply);
    connect(reply, &QNetworkReply::finished, this, [=](){
        this->_replys.remove(reply);
        on_reply_finished(reply);
        QTimer::singleShot(0, this, [=](){
            QPushButton* btn = new QPushButton("下一页", this);
            btn->setMinimumSize(QSize(245, 55));
            btn->setMaximumSize(QSize(245, 55));
            btn->setStyleSheet("QPushButton { background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1,stop:0 #f8f1f8, stop:1 #fbe6ee);border: none;border-radius: 12px;padding: 12px;}QPushButton:hover {background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1,stop:0 #fcdfea, stop:1 #f8c7e1);}");
            ui->container->layout()->addWidget(btn);
            connect(btn, &QPushButton::clicked, this, [=](){
                pageSearch(searchText, limit, offset + limit);
                ui->container->layout()->removeWidget(btn);
                btn->deleteLater();
            });
        });
    });
}

void SearchListWidget::clearOldDatas()
{
    auto r = _replys; _replys.clear();
    for(auto& reply : r){
        reply->deleteLater();
    }

    auto s = _songItems; _songItems.clear();
    for(int i = 0; i < s.size(); i++){
        ui->container->layout()->removeWidget(s[i]);
        s[i]->deleteLater();
    }

    _id.clear();
}

void SearchListWidget::updateSearchText()
{
    QString htmlText = "<span style='font-family:Microsoft YaHei; font-size:33px; font-weight:bold; color:#202020;'>" + _old_searchText + "</span>   "
                       "<span style='font-family:Microsoft YaHei; font-size:20px; color:#9ca3af;'>的相关搜索如下，找到" + QString::number(_songItems.size()) +"首单曲</span>";
    ui->label_searchText->setText(htmlText);
    ui->label_searchText->setTextFormat(Qt::RichText);  // 确保是富文本模式
}

void SearchListWidget::setSearchText(const QString& searchText)
{
    QString htmlText = "<span style='font-family:Microsoft YaHei; font-size:33px; font-weight:bold; color:#202020;'>" + searchText + "</span>   "
                       "<span style='font-family:Microsoft YaHei; font-size:20px; color:#9ca3af;'>的相关搜索如下，找到" + QString::number(_songItems.size()) +"首单曲</span>";
    ui->label_searchText->setText(htmlText);
    ui->label_searchText->setTextFormat(Qt::RichText);  // 确保是富文本模式
}

void SearchListWidget::getPicUrlByAlbumId(int index, qint64 albumId)
{
    if(albumId){ // url->request->get-reply->connect{data->doc->root->...|deleteLater}
        QString albumUrl = "https://music.163.com/api/album/" + QString::number(albumId);
        QNetworkRequest albumRequest((QUrl(albumUrl)));
        QNetworkReply *albumReply = _manager->get(albumRequest);
        _replys.insert(albumReply);
        connect(albumReply, &QNetworkReply::finished, [=]() {
            this->_replys.remove(albumReply);
            if (albumReply->error() == QNetworkReply::NoError) {
                QByteArray albumData = albumReply->readAll();
                QJsonDocument albumDoc = QJsonDocument::fromJson(albumData);
                QJsonObject albumRoot = albumDoc.object();
                QString picUrl = albumRoot.value("album").toObject().value("picUrl").toString();
                // 获取到了url,可以再次发起请求,这次返回的数据就是我们要的图片了
                QNetworkRequest imageRequest((QUrl(picUrl)));
                QNetworkReply *imageReply = _manager->get(imageRequest);
                _replys.insert(imageReply);
                connect(imageReply, &QNetworkReply::finished, [=]() {
                    this->_replys.remove(imageReply);
                    this->on_imageReply_finished(index, imageReply);
                });

                // 本想通过专辑找歌曲id的,结果发现单曲搜索不给id的,这里也不给id
//                QJsonArray songs = albumRoot.value("album").toObject().value("songs").toArray();
//                qDebug() << "专辑共包含歌曲数：" << songs.count();
//                for (const QJsonValue &songValue : songs) {
//                    QJsonObject song = songValue.toObject();
//                    // 提取歌曲名和ID
//                    QString name = song["name"].toString();
//                    int id = song["id"].toInt();
//                    qDebug() << "歌曲: " << name << ", id: " << id;
//                }
            }
            albumReply->deleteLater();
        });
    } else { // 如果album也没有,那只能加载默认图了
        QNetworkRequest imageRequest((QUrl("https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg")));
        QNetworkReply *imageReply = _manager->get(imageRequest);
        _replys.insert(imageReply);
        connect(imageReply, &QNetworkReply::finished, [=]() {
            this->_replys.remove(imageReply);
            this->on_imageReply_finished(index, imageReply);
        });
    }
}

void SearchListWidget::getSongUrl(SongItemWidget *songItem, qint64 songId)
{
    QString urlStr = "http://music.163.com/song/media/outer/url?id=" + QString::number(songId) + ".mp3";
    QNetworkRequest request;
    request.setUrl(QUrl(urlStr));
    QNetworkReply* reply = _manager->get(request);
    _replys.insert(reply);
    connect(reply, &QNetworkReply::finished, this, [=](){
        this->_replys.remove(reply);
        if(reply->error() != QNetworkReply::NoError){
            qDebug() << "请求出错: " << reply->errorString();
            reply->deleteLater();
            return;
        }
        // 这里一定会重定向的,一定,吧
        QUrl songUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
        if(songUrl.isEmpty() || songUrl == QUrl("http://music.163.com/404")){
            qDebug() << "没用的songUrl";
            songItem->setDuration(0);
        } else {
//            songItem->setUrl(songUrl);
            songItem->setUrl(urlStr);
//            songItem->connectManager();
        }
        reply->deleteLater();
    });
}


void SearchListWidget::on_pushButton_playAll_clicked()
{
    QVector<QUrl> songs;
    for(auto& e : _songItems){
//        if(e->isConnected()){
//            songs.push_back(e->songItem().url());
//        }
        if (e->songItem().duration == 0)
            continue;
        if (e->isConnected() == false)
            e->connectManager();
        songs.push_back(e->songItem().url());
    }
    emit playAll(songs);
}

void SearchListWidget::on_reply_finished(QNetworkReply* reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "请求错误：" << reply->errorString();
        reply->deleteLater();
        return;
    }

    QByteArray rawData = reply->readAll();
//    qDebug() << "-------------------------\n" << QString(rawData) << "\n-------------------------";
//    当limit=1, searchText="da capo"时返回的数据:
//     "{\"result\":{\"songs\":[{\"id\":2026565329,\"name\":\"Da Capo\",\"artists\":[{\"id\":12487174,\"name\":\"HOYO-MiX\",\"picUrl\":null,\"alias\":[],\"albumSize\":0,\"picId\":0,\"fansGroup\":null,\"img1v1Url\":\"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1\":0,\"trans\":null}],\"album\":{\"id\":160968964,\"name\":\"Da Capo\",\"artist\":{\"id\":0,\"name\":\"\",\"picUrl\":null,\"alias\":[],\"albumSize\":0,\"picId\":0,\"fansGroup\":null,\"img1v1Url\":\"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1\":0,\"trans\":null},\"publishTime\":1677772800000,\"size\":2,\"copyrightId\":2710647,\"status\":1,\"picId\":109951168434956885,\"mark\":0},\"duration\":134594,\"copyrightId\":2710647,\"status\":0,\"alias\":[\"崩坏3《毕业旅行》动画短片印象曲\"],\"rtype\":0,\"ftype\":0,\"mvid\":14645046,\"fee\":0,\"rUrl\":null,\"alias\":[\"崩坏3《毕业旅行》动画短片印象曲\"],\"mark\":537133184}],\"songCount\":306},\"code\":200}"
//    下面将按照这个格式进行解析：

    QJsonDocument doc = QJsonDocument::fromJson(rawData);
    if (!doc.isObject()) {
        qDebug() << "根节点不是JSON对象";
        return;
    }
    QJsonObject root = doc.object();
    QJsonObject result = root.value("result").toObject();
    QJsonArray songs = result.value("songs").toArray();

    const int size = songs.size();
    qDebug() << "songs.size() = " << size;
    for(int i = 0; i < size; i++)
        QTimer::singleShot(0, this, [=]() {
        addSongItem(new SongItemWidget(this));
    });
    QTimer::singleShot(66, this, [=]() {
    _id.resize(size);
    updateSearchText();
    for(int i = 0; i < size; i++) _id[i] = 0;
    for(int i = 0; i < size; i++){
        QJsonObject song = songs[i].toObject();
        // 获取到每个song的信息,然后在里面找想要的
        // 这里每获取一个信息就测试一下,其实还挺好做的(除了图片)
        // 1. 名字
        QString name = song.value("name").toString(); // 名字
        _songItems[i]->setName(name);
        // 2. 歌手, 这是个[]
        QString str_artist; // 注:网易云音乐的歌手是个button组,这里简化为一个button,且点击无反应
        QJsonArray artists = song.value("artists").toArray();
        qDebug() << "artists size = " << artists.size();
        for(int i = 0; i < artists.size(); i++){
            QJsonObject artist = artists[i].toObject();
            if(str_artist.size()) str_artist += " / ";
            str_artist += artist.value("name").toString();
        }
        _songItems[i]->setArtist(str_artist);
        // 3. 专辑
        QJsonObject album = song.value("album").toObject();
        QString str_album = album.value("name").toString();
        _songItems[i]->setAlbum(str_album);
        // 4. 时长
        int duration = song.value("duration").toInt();
        _songItems[i]->setDuration(duration);
        // 5. id,这个是播放的关键,我们要用id拼接出url
        _id[i] = song.value("id").toVariant().toLongLong(); // 嘛,不过这里获取的id极为有限,vip歌曲的id是一定没有的
                                                            // 补,这里必须用longlong,用int会炸,比如Dye the sky的id是2657747230
        if(_id[i]){
            _songItems[i]->songItem().wangyiyun_id = _id[i];
            QString urlStr = "http://music.163.com/song/media/outer/url?id=" + QString::number(_id[i]) + ".mp3";
            qDebug() << urlStr;
//            if (SongManager::instance()->getSongItem(&_songItems[i]->songItem(), urlStr))
            if(SongManager::instance()->exist(urlStr)){
                _songItems[i]->setUrl(urlStr);
                _songItems[i]->connectManager();
                _songItems[i]->setImage(_songItems[i]->songItem().image); // 这里得手动设置一下
                continue;
            }
            else
                getSongUrl(_songItems[i], _id[i]);
        } else {
            _songItems[i]->setDuration(0); // id都没,那就让时长为0吧
        }
        // 6. 图片
        // 首先我们看见,单曲搜索的返回信息只有图片的picId,而picUrl是黑白的默认图片
        // 我去找了找,没有找到用图片id拼出图片url的方法
        // 于是我想,似乎每首歌都有id,能否通过id找歌曲的详细信息?
        // 下面是https://music.163.com/api/song/detail/?id=2026565329&ids=[2026565329]的返回结果:
        //  "{\"songs\":[{\"name\":\"Da Capo\",\"id\":2026565329,\"position\":0,\"alias\":[\"崩坏3《毕业旅行》动画短片印象曲\"],\"status\":0,\"fee\":0,\"copyrightId\":2710647,\"disc\":\"01\",\"no\":1,\"artists\":[{\"name\":\"HOYO-MiX\",\"id\":12487174,\"picId\":0,\"img1v1Id\":0,\"briefDesc\":\"\",\"picUrl\":\"https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"albumSize\":0,\"alias\":[],\"trans\":\"\",\"musicSize\":0,\"topicPerson\":0}],\"album\":{\"name\":\"Da Capo\",\"id\":160968964,\"type\":\"Single\",\"size\":2,\"picId\":109951168434956885,\"blurPicUrl\":\"https://p1.music.126.net/awzv1LpuBJiKTeB7roh_Aw==/109951168434956885.jpg\",\"companyId\":0,\"pic\":109951168434956885,\"picUrl\":\"https://p1.music.126.net/awzv1LpuBJiKTeB7roh_Aw==/109951168434956885.jpg\",\"publishTime\":1677772800000,\"description\":\"\",\"tags\":\"\",\"company\":\"miHoYo\",\"briefDesc\":\"\",\"artist\":{\"name\":\"\",\"id\":0,\"picId\":0,\"img1v1Id\":0,\"briefDesc\":\"\",\"picUrl\":\"https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"albumSize\":0,\"alias\":[],\"trans\":\"\",\"musicSize\":0,\"topicPerson\":0},\"songs\":[],\"alias\":[],\"status\":1,\"copyrightId\":2710647,\"commentThreadId\":\"R_AL_3_160968964\",\"artists\":[{\"name\":\"HOYO-MiX\",\"id\":12487174,\"picId\":0,\"img1v1Id\":0,\"briefDesc\":\"\",\"picUrl\":\"https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"albumSize\":0,\"alias\":[],\"trans\":\"\",\"musicSize\":0,\"topicPerson\":0}],\"subType\":\"录音室版\",\"transName\":null,\"onSale\":false,\"mark\":0,\"gapless\":0,\"dolbyMark\":0,\"picId_str\":\"109951168434956885\"},\"starred\":false,\"popularity\":100.0,\"score\":100,\"starredNum\":0,\"duration\":134594,\"playedNum\":0,\"dayPlays\":0,\"hearTime\":0,\"sqMusic\":{\"name\":null,\"id\":7934831164,\"size\":17174709,\"extension\":\"flac\",\"sr\":48000,\"dfsId\":0,\"bitrate\":1020826,\"playTime\":134594,\"volumeDelta\":-49611.0},\"hrMusic\":{\"name\":null,\"id\":7934831162,\"size\":30133067,\"extension\":\"flac\",\"sr\":48000,\"dfsId\":0,\"bitrate\":1791041,\"playTime\":134594,\"volumeDelta\":-50327.0},\"ringtone\":\"\",\"crbt\":null,\"audition\":null,\"copyFrom\":\"\",\"commentThreadId\":\"R_SO_4_2026565329\",\"rtUrl\":null,\"ftype\":0,\"rtUrls\":[],\"copyright\":0,\"transName\":null,\"sign\":null,\"mark\":0,\"originCoverType\":1,\"originSongSimpleData\":null,\"single\":0,\"noCopyrightRcmd\":null,\"mvid\":14645046,\"hMusic\":{\"name\":null,\"id\":7934831165,\"size\":5386605,\"extension\":\"mp3\",\"sr\":48000,\"dfsId\":0,\"bitrate\":320000,\"playTime\":134594,\"volumeDelta\":-50328.0},\"mMusic\":{\"name\":null,\"id\":7934831158,\"size\":3231981,\"extension\":\"mp3\",\"sr\":48000,\"dfsId\":0,\"bitrate\":192000,\"playTime\":134594,\"volumeDelta\":-47887.0},\"lMusic\":{\"name\":null,\"id\":7934831159,\"size\":2154669,\"extension\":\"mp3\",\"sr\":48000,\"dfsId\":0,\"bitrate\":128000,\"playTime\":134594,\"volumeDelta\":-46716.0},\"bMusic\":{\"name\":null,\"id\":7934831159,\"size\":2154669,\"extension\":\"mp3\",\"sr\":48000,\"dfsId\":0,\"bitrate\":128000,\"playTime\":134594,\"volumeDelta\":-46716.0},\"mp3Url\":null,\"rtype\":0,\"rurl\":null}],\"equalizers\":{},\"code\":200}"
        // 可以发现,唯一一个有效的picUrl是专辑里的.
        // 而歌曲的封面就是专辑的封面,因此等会儿的目标就是直接用专辑id找专辑封面.
        // 下面是https://music.163.com/api/album/160968964的返回结果:
        //  "{\"code\":200,\"album\":{\"songs\":[{\"starred\":false,\"popularity\":100.0,\"starredNum\":0,\"playedNum\":0,\"dayPlays\":0,\"hearTime\":0,\"mp3Url\":\"http://m2.music.126.net/hmZoNQaqzZALvVp0rE7faA==/0.mp3\",\"rtUrls\":null,\"mark\":537133184,\"noCopyrightRcmd\":null,\"originCoverType\":0,\"originSongSimpleData\":null,\"songJumpInfo\":null,\"artists\":[{\"img1v1Id\":18686200114669622,\"topicPerson\":0,\"picId\":0,\"briefDesc\":\"\",\"musicSize\":0,\"albumSize\":0,\"picUrl\":\"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p2.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg\",\"followed\":false,\"trans\":\"\",\"alias\":[],\"name\":\"HOYO-MiX\",\"id\":12487174,\"img1v1Id_str\":\"18686200114669622\"}],\"copyrightId\":2710647,\"album\":{\"songs\":[],\"paid\":false,\"onSale\":false,\"mark\":0,\"awardTags\":null,\"displayTags\":null,\"publishTime\":1677772800000,\"artists\":[{\"img1v1Id\":18686200114669622,\"topicPerson\":0,\"picId\":0,\"briefDesc\":\"\",\"musicSize\":0,\"albumSize\":0,\"picUrl\":\"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p2.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg\",\"followed\":false,\"trans\":\"\",\"alias\":[],\"name\":\"HOYO-MiX\",\"id\":12487174,\"img1v1Id_str\":\"18686200114669622\"}],\"copyrightId\":2710647,\"picId\":109951168434956885,\"artist\":{\"img1v1Id\":18686200114669622,\"topicPerson\":0,\"picId\":0,\"briefDesc\":\"\",\"musicSize\":0,\"albumSize\":0,\"picUrl\":\"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p2.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg\",\"followed\":false,\"trans\":\"\",\"alias\":[],\"name\":\"\",\"id\":0,\"img1v1Id_str\":\"18686200114669622\"},\"company\":\"miHoYo\",\"briefDesc\":\"\",\"picUrl\":\"https://p2.music.126.net/awzv1LpuBJiKTeB7roh_Aw==/109951168434956885.jpg\",\"commentThreadId\":\"R_AL_3_160968964\",\"blurPicUrl\":\"https://p2.music.126.net/awzv1LpuBJiKTeB7roh_Aw==/109951168434956885.jpg\",\"companyId\":0,\"pic\":109951168434956885,\"status\":1,\"subType\":\"录音室版\",\"description\":\"\",\"tags\":\"\",\"alias\":[],\"name\":\"Da Capo\",\"id\":160968964,\"type\":\"Single\",\"size\":2,\"picId_str\":\"109951168434956885\"},\"score\":100,\"audition\":null,\"copyFrom\":\"\",\"ringtone\":\"\",\"disc\":\"01\",\"no\":1,\"fee\":0,\"hMusic\":{\"volumeDelta\":-50328.0,\"bitrate\":320000,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831165,\"size\":5386605,\"extension\":\"mp3\"},\"mMusic\":{\"volumeDelta\":-47887.0,\"bitrate\":192000,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831158,\"size\":3231981,\"extension\":\"mp3\"},\"lMusic\":{\"volumeDelta\":-46716.0,\"bitrate\":128000,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831159,\"size\":2154669,\"extension\":\"mp3\"},\"commentThreadId\":\"R_SO_4_2026565329\",\"mvid\":14645046,\"crbt\":null,\"rtUrl\":null,\"ftype\":0,\"bMusic\":{\"volumeDelta\":-46716.0,\"bitrate\":128000,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831159,\"size\":2154669,\"extension\":\"mp3\"},\"sqMusic\":{\"volumeDelta\":-49611.0,\"bitrate\":1020826,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831164,\"size\":17174709,\"extension\":\"flac\"},\"hrMusic\":{\"volumeDelta\":-50327.0,\"bitrate\":1791041,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831162,\"size\":30133067,\"extension\":\"flac\"},\"rtype\":0,\"rurl\":null,\"position\":0,\"duration\":134594,\"status\":0,\"alias\":[\"崩坏3《毕业旅行》动画短片印象曲\"],\"name\":\"Da Capo\",\"id\":2026565329},{\"starred\":false,\"popularity\":100.0,\"starredNum\":0,\"playedNum\":0,\"dayPlays\":0,\"hearTime\":0,\"mp3Url\":\"http://m2.music.126.net/hmZoNQaqzZALvVp0rE7faA==/0.mp3\",\"rtUrls\":null,\"mark\":536870912,\"noCopyrightRcmd\":null,\"originCoverType\":0,\"originSongSimpleData\":null,\"songJumpInfo\":null,\"artists\":[{\"img1v1Id\":18686200114669622,\"topicPerson\":0,\"picId\":0,\"briefDesc\":\"\",\"musicSize\":0,\"albumSize\":0,\"picUrl\":\"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p2.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg\",\"followed\":false,\"trans\":\"\",\"alias\":[],\"name\":\"HOYO-MiX\",\"id\":12487174,\"img1v1Id_str\":\"18686200114669622\"}],\"copyrightId\":2710647,\"album\":{\"songs\":[],\"paid\":false,\"onSale\":false,\"mark\":0,\"awardTags\":null,\"displayTags\":null,\"publishTime\":1677772800000,\"artists\":[{\"img1v1Id\":18686200114669622,\"topicPerson\":0,\"picId\":0,\"briefDesc\":\"\",\"musicSize\":0,\"albumSize\":0,\"picUrl\":\"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p2.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg\",\"followed\":false,\"trans\":\"\",\"alias\":[],\"name\":\"HOYO-MiX\",\"id\":12487174,\"img1v1Id_str\":\"18686200114669622\"}],\"copyrightId\":2710647,\"picId\":109951168434956885,\"artist\":{\"img1v1Id\":18686200114669622,\"topicPerson\":0,\"picId\":0,\"briefDesc\":\"\",\"musicSize\":0,\"albumSize\":0,\"picUrl\":\"https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p2.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg\",\"followed\":false,\"trans\":\"\",\"alias\":[],\"name\":\"\",\"id\":0,\"img1v1Id_str\":\"18686200114669622\"},\"company\":\"miHoYo\",\"briefDesc\":\"\",\"picUrl\":\"https://p2.music.126.net/awzv1LpuBJiKTeB7roh_Aw==/109951168434956885.jpg\",\"commentThreadId\":\"R_AL_3_160968964\",\"blurPicUrl\":\"https://p2.music.126.net/awzv1LpuBJiKTeB7roh_Aw==/109951168434956885.jpg\",\"companyId\":0,\"pic\":109951168434956885,\"status\":1,\"subType\":\"录音室版\",\"description\":\"\",\"tags\":\"\",\"alias\":[],\"name\":\"Da Capo\",\"id\":160968964,\"type\":\"Single\",\"size\":2,\"picId_str\":\"109951168434956885\"},\"score\":100,\"audition\":null,\"copyFrom\":\"\",\"ringtone\":\"\",\"disc\":\"01\",\"no\":2,\"fee\":0,\"hMusic\":{\"volumeDelta\":-33303.0,\"bitrate\":320000,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831016,\"size\":5386605,\"extension\":\"mp3\"},\"mMusic\":{\"volumeDelta\":-30906.0,\"bitrate\":192000,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831019,\"size\":3231981,\"extension\":\"mp3\"},\"lMusic\":{\"volumeDelta\":-29756.0,\"bitrate\":128000,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831020,\"size\":2154669,\"extension\":\"mp3\"},\"commentThreadId\":\"R_SO_4_2026571661\",\"mvid\":0,\"crbt\":null,\"rtUrl\":null,\"ftype\":0,\"bMusic\":{\"volumeDelta\":-29756.0,\"bitrate\":128000,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831020,\"size\":2154669,\"extension\":\"mp3\"},\"sqMusic\":{\"volumeDelta\":-34685.0,\"bitrate\":907902,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831023,\"size\":15274849,\"extension\":\"flac\"},\"hrMusic\":{\"volumeDelta\":-33253.0,\"bitrate\":1674339,\"playTime\":134594,\"dfsId\":0,\"sr\":48000,\"name\":\"\",\"id\":7934831021,\"size\":28169625,\"extension\":\"flac\"},\"rtype\":0,\"rurl\":null,\"position\":0,\"duration\":134594,\"status\":0,\"alias\":[],\"name\":\"Da Capo (伴奏)\",\"id\":2026571661}],\"paid\":false,\"onSale\":false,\"mark\":0,\"awardTags\":null,\"displayTags\":null,\"publishTime\":1677772800000,\"artists\":[{\"img1v1Id\":18686200114669622,\"topicPerson\":0,\"picId\":0,\"briefDesc\":\"\",\"musicSize\":0,\"albumSize\":0,\"picUrl\":\"https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg\",\"img1v1Url\":\"https://p1.music.126.net/VnZiScyynLG7atLIZ2YPkw==/18686200114669622.jpg\",\"followed\":false,\"trans\":\"\",\"alias\":[],\"name\":\"HOYO-MiX\",\"id\":12487174,\"img1v1Id_str\":\"18686200114669622\"}],\"copyrightId\":2710647,\"picId\":109951168434956885,\"artist\":{\"img1v1Id\":109951168127138041,\"topicPerson\":0,\"picId\":109951164496484854,\"briefDesc\":\"\",\"musicSize\":2768,\"albumSize\":71,\"picUrl\":\"https://p1.music.126.net/JsIJaz49qG0NAeHLUxKqDw==/109951164496484854.jpg\",\"img1v1Url\":\"https://p1.music.126.net/Y2_BNSAyXLMHztZWCfUKKA==/109951168127138041.jpg\",\"followed\":false,\"trans\":\"\",\"alias\":[],\"name\":\"HOYO-MiX\",\"id\":12487174,\"picId_str\":\"109951164496484854\",\"img1v1Id_str\":\"109951168127138041\"},\"company\":\"miHoYo\",\"briefDesc\":\"\",\"picUrl\":\"https://p1.music.126.net/awzv1LpuBJiKTeB7roh_Aw==/109951168434956885.jpg\",\"commentThreadId\":\"R_AL_3_160968964\",\"blurPicUrl\":\"https://p1.music.126.net/awzv1LpuBJiKTeB7roh_Aw==/109951168434956885.jpg\",\"companyId\":0,\"pic\":109951168434956885,\"status\":1,\"subType\":\"录音室版\",\"description\":\"\",\"tags\":\"\",\"alias\":[],\"name\":\"Da Capo\",\"id\":160968964,\"type\":\"Single\",\"size\":2,\"picId_str\":\"109951168434956885\",\"info\":{\"commentThread\":{\"id\":\"R_AL_3_160968964\",\"resourceInfo\":{\"id\":160968964,\"userId\":-1,\"name\":\"Da Capo\",\"imgUrl\":\"https://p1.music.126.net/awzv1LpuBJiKTeB7roh_Aw==/109951168434956885.jpg\",\"creator\":null,\"encodedId\":null,\"subTitle\":null,\"webUrl\":null},\"resourceType\":3,\"commentCount\":533,\"likedCount\":0,\"shareCount\":401,\"hotCount\":6,\"latestLikedUsers\":null,\"resourceId\":160968964,\"resourceOwnerId\":-1,\"resourceTitle\":\"Da Capo\"},\"latestLikedUsers\":null,\"liked\":false,\"comments\":null,\"resourceType\":3,\"resourceId\":160968964,\"commentCount\":533,\"likedCount\":0,\"shareCount\":401,\"threadId\":\"R_AL_3_160968964\"}}}"
        // 顺带,有的id在刚刚单曲搜索中的值为0,我们也可以尝试在专辑中,通过歌曲名找id,不过我感觉意义不大,这里就不搞了(补:经过实验,确实没用)
        int albumId = song.value("album").toObject().value("id").toInt();
        qDebug() << albumId;
        getPicUrlByAlbumId(i, albumId);
    }
    });
}
void SearchListWidget::on_imageReply_finished(int index, QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "请求错误：" << reply->errorString();
        reply->deleteLater();
        return;
    }
    if (index >= _songItems.size()){
        qDebug() << "index >= _songItems.size()";
        reply->deleteLater();
        return;
    }
    QByteArray data = reply->readAll();
    QPixmap pixmap;
    pixmap.loadFromData(data);
    _songItems[index]->setImage(pixmap);
//    _songItems[index]->connectManager();
    reply->deleteLater();
}

void SearchListWidget::on_songItem_played(int index, bool play)
{
    qDebug() << index;
    emit played(_songItems[index]->songItem(), play);
}

void SearchListWidget::on_pushButton_favoriteAll_clicked()
{
    static bool jug = true;
    if(jug){
//        ui->scrollArea->hide();
        ui->scrollArea->lower();
    } else {
//        ui->scrollArea->show();
        ui->scrollArea->raise();
    }
    jug = !jug;
}
